/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

import buildURL from "../../node_modules/axios/lib/helpers/buildURL"
import buildFullPath from "../../node_modules/axios/lib/core/buildFullPath"
import settle from "../../node_modules/axios/lib/core/settle"
import AxiosError from '../../node_modules/axios/lib/core/AxiosError'
import request from '@ohos.request';

function download(config, resolve, reject){
    var downloadTask ;
    let context = config.context
    let fullPath = buildFullPath(config.baseURL, config.url);

    function settleResult(request, data, code){
        let response = {
            data: data,
            status: code,
            statusText: "",
            headers: config.header,
            config: config,
            request: request
        };
        settle(function _resolve(value) {
            resolve(value);
        }, function _reject(err) {
            reject(err);
        }, response);
    }
    // url校验
    if(!fullPath){
        reject(new AxiosError("Cannot read properties of url!", AxiosError.ERR_BAD_OPTION, config, null, null));
        return
    }else if(typeof(fullPath) !== 'string'){
        reject(new AxiosError("Url type should be character type！", AxiosError.ERR_BAD_OPTION_VALUE, config, null, null));
        return
    }
    // 构建配置参数
    let options = {
        url: buildURL(fullPath, config.params, config.paramsSerializer),
        description: 'download file!',
        enableRoaming: true,
        enableMetered: true,
        title: 'download',
        header: config.headers || {}
    }
    // 添加filePath
    if(config.filePath){
        options.filePath = config.filePath
    }
    // 发送下载请求
    request.download(context, options).then((data) => {

        downloadTask = data
        if (typeof config.onDownloadProgress === 'function') {
            downloadTask.on('progress', (loaded, total)=>{
                // onDownloadProgress的参数只有一个progressEvent，构建progressEvent
                config.onDownloadProgress({
                    loaded: loaded,
                    total: total
                })
            })
        }

        // 下载失败
        downloadTask.on('fail', function callBack(err) {
            reject(new AxiosError(err, null, config, request, request));
        });
        // 完成下载
        downloadTask.on('complete', () => {
            settleResult(request, 'download success!', 200)
        })
    }).catch(error=>{
        reject(new AxiosError(error, AxiosError.ERR_NETWORK, config, request, request));
    })
}

export default download
